const App = getApp();
const db = wx.cloud.database();
const _ = db.command;
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 上传弹窗
    show: false,
    // 新增附件按钮
    btnloading: false,
    // 信息列表展开
    folderShow: false,
    // 文件列表展开
    folderFileShow: true,
    // 文件详情
    folder: "",
    // 下载弹窗
    modalName: "",
    // 详情弹窗
    folderDetailsShow: "",
    // 文件详情
    folderDetails: "",
    // 下载回来的文件链接地址
    downloadFilePath: "",
    //  上传权限
    pickerIdx: null,
    picker: ['仅创建人', '所有成员'],

    // 更新列表和上传列表
    setFolder: {
      name: "",
      UploadPermission: "",
      file: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this
    let classid = JSON.parse(decodeURIComponent(options.passData))
    console.log('传值过来的值', classid);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      classid,
      UserInfo
    })
    that.getFolderDetails()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 上传更新弹窗
  showPopup() {
    this.setData({
      show: true
    });
  },
  // 关闭上传更新弹窗
  onClose() {
    this.setData({
      show: false
    });
  },
  // 展开搜索
  folderShow() {
    that.setData({
      folderShow: !that.data.folderShow
    })
  },
  // 展开文件列表
  folderFileShow() {
    that.setData({
      folderFileShow: !that.data.folderFileShow
    })
  },
  // 上传权限
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let picker = that.data.picker
    that.setData({
      pickerIdx: e.detail.value,
      'setFolder.UploadPermission': picker[e.detail.value]
    })
  },
  // 获得input值
  handleChange(e) {
    console.log(e.detail.value);
    let value = e.detail.value
    value = value.replace(/^\s*/, "");
    console.log('value', value);
    this.setData({
      ['setFolder.name']: value
    })
  },
  // 获取文件库详情
  getFolderDetails() {
    App.toast.showLoading('加载中')
    db.collection('folder').where({
        classId: that.data.classid
      })
      .get({
        success: function (res) {
          App.toast.hideLoading()
          let list = res.data[0]
          let picker = that.data.picker
          let pickerIdx = picker.findIndex(item => item == list.UploadPermission)
          console.log('找到权限的下标', pickerIdx);
          console.log('文件库详情', list)
          that.setData({
            folder: list,
            'setFolder.file': list.file,
            'setFolder.name': list.name,
            'setFolder.UploadPermission': list.UploadPermission,
            pickerIdx: pickerIdx,
          })
        }
      })
  },

  // 下载文件到本地
  downloadFile(e) {
    let fileid = e.currentTarget.dataset.fileid
    console.log('fileid', fileid);
    // 如果是打开详情再下载的，那就把详情弹窗关掉先
    that.setData({
      folderDetailsShow: null
    })
    App.toast.showLoading('下载中')
    wx.cloud.getTempFileURL({
      fileList: [{
        fileID: fileid,
      }]
    }).then(res => {
      App.toast.hideLoading()
      console.log('返回来的链接', res.fileList[0])
      that.setData({
        modalName: "downloadShow",
        downloadFilePath: res.fileList[0].tempFileURL,
      })
    }).catch(error => {
      console.error(error)
    })
  },

  // 关闭下载弹窗
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  // 打开详情弹窗
  DetailsShow(e) {
    let data = e.currentTarget.dataset
    console.log(data);
    that.setData({
      folderDetails: data.folder,
      folderDetailsShow: data.show,
    })
  },
  // 关闭详情弹窗
  CloseFolderDetails(e) {
    this.setData({
      folderDetailsShow: null
    })
  },


  // 复制文件链接地址
  codeFilePath(e) {
    console.log(e.currentTarget.dataset);
    let filepath = e.currentTarget.dataset.filepath
    wx.setClipboardData({
      data: filepath,
      success: res => {
        console.log(res);
        App.toast.showToast('链接已经复制', 'none', 1000)
        that.hideModal()
      }
    })
  },

  // 上传附件
  addfile() {
    that.setData({
      btnloading: true
    })
    wx.chooseMessageFile({
      count: 20,
      type: 'all',
      success(res) {
        console.log(res);
        let data = res.tempFiles
        console.log(data);
        const uploadTasks = data.map((file, index) => {
          let cloudPath = "folder/" + that.data.folder.name + "/" + that.data.UserInfo.nickName + "/" + file.name
          return wx.cloud.uploadFile({
            cloudPath: cloudPath,
            filePath: file.path
          });
        });
        Promise.all(uploadTasks)
          .then(res => {
            let list = []
            res.forEach((item, index) => {
              list.push({
                name: data[index].name,
                size: (data[index].size / 1024 / 1024).toFixed(2),
                id: item.fileID,
                type: data[index].type,
                timeTs: Date.now(),
                UploadUsers: that.data.UserInfo.nickName,
                fileId: Date.now() + index
              })
            })
            let fileList = that.data.setFolder.file
            list.forEach(item => {
              fileList.push(item)
            })
            console.log('fileList', fileList);
            that.setData({
              ['setFolder.file']: fileList,
              btnloading: false
            })
          })
          .catch(e => {
            that.setData({
              btnloading: false
            })
            console.log(e);
          });
      },
      fail: function (res) {
        that.setData({
          btnloading: false
        })
      }
    })
  },

  // 删除附件
  removefileName(e) {
    const {
      index
    } = e.currentTarget.dataset
    console.log(index);
    let fileList = that.data.setFolder.file
    console.log(fileList.splice(index, 1));
    that.setData({
      ['setFolder.file']: fileList,
    })
  },


  // 更新文件库
  setFolder(e) {
    console.log(e.currentTarget.dataset);
    let id = e.currentTarget.dataset.id
    let setFolder = that.data.setFolder
    App.toast.showLoading('更新中')
    db.collection('folder').where({
      _id: id
    }).update({
      data: {
        name: setFolder.name,
        UploadPermission: setFolder.UploadPermission,
        file: setFolder.file
      },
      success: function (res) {
        App.toast.hideLoading()
        console.log('更新成功', res);
        that.getFolderDetails()
        that.onClose()
      }
    })
  },

  // 成员上传文件
  memberUploadFile(e) {
    let data = e.currentTarget.dataset
    console.log('data', data);
    if (data.uploadpermission === '仅创建人') {
      App.toast.showToast('你没有权限上传，请联系创建人')
      return
    }
    // 文件库id
    let id = data.id
    App.toast.showLoading('上传中')
    wx.chooseMessageFile({
      count: 10,
      type: 'all',
      success(res) {
        console.log(res);
        let data = res.tempFiles
        console.log(data);
        const uploadTasks = data.map((file, index) => {
          let cloudPath = "folder/" + that.data.folder.name + "/" + that.data.UserInfo.nickName + "/" + file.name
          return wx.cloud.uploadFile({
            cloudPath: cloudPath,
            filePath: file.path
          });
        });
        Promise.all(uploadTasks)
          .then(res => {
            App.toast.hideLoading()
            let list = []
            res.forEach((item, index) => {
              list.push({
                name: data[index].name,
                size: (data[index].size / 1024 / 1024).toFixed(2),
                id: item.fileID,
                type: data[index].type,
                timeTs: Date.now(),
                UploadUsers: that.data.UserInfo.nickName,
                UploadUsersId: that.data.UserInfo.account,
                fileId: Date.now() + index
              })
            })
            return list
          })
          .then(list => {
            // 获取到已经上传云储存的文件
            console.log('list', list);
            App.toast.showLoading('上传中')
            db.collection('folder').where({
              _id: id
            }).update({
              data: {
                file: _.push(list)
              },
              success: function (res) {
                App.toast.hideLoading()
                console.log('上传成功', res);
                setTimeout(() => {
                  // 重新更新文件库
                  that.getFolderDetails()
                }, 1000)
              }
            })
          })
          .catch(e => {
            App.toast.hideLoading()
            that.setData({

            })
            console.log(e);
          });
      },
      fail: function (res) {
        App.toast.hideLoading()
      }
    })
  },

  // 成员删除自己的文件
  memberRemoverFolder(e) {
    let folder = e.currentTarget.dataset.folder
    console.log('folder', folder);
    that.CloseFolderDetails()
    App.toast.showLoading('删除中')
    db.collection('folder').where(_.and([{
      classId: that.data.classid,
      'file.UploadUsersId': folder.UploadUsersId
    }, ])).update({
      data: {
        file: _.pull({
          fileId: _.eq(folder.fileId)
        })
      },
      success: function (res) {
        App.toast.hideLoading()
        that.getFolderDetails()
        console.log('删除成功', res);
      }
    })
  },

  // 删除文件库
  removeFoldaer(e) {
    let id = e.currentTarget.dataset.id
    console.log(id);
    wx.showModal({
      title: '提示',
      content: '是否删除该文件库',
      success(res) {
        if (res.confirm) {
          App.toast.showLoading()
          db.collection('folder').doc(id).remove({
            success: function (res) {
              App.toast.hideLoading()
              console.log('删除成功', res.data)
              App.toast.showToast('删除成功，正在返回')
              setTimeout(() => {
                App.route.relBack('/pages/folder/list/index')
              }, 1500)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

})